package com.wyl.wyl.testapplication.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.util.ResourceUtil;
import com.iflytek.cloud.util.ResourceUtil.RESOURCE_TYPE;
import com.marquee.dingrui.marqueeviewlib.MarqueeView;
import com.wyl.wyl.testapplication.Api;
import com.wyl.wyl.testapplication.R;
import com.wyl.wyl.testapplication.adapter.LineingAdapter;
import com.wyl.wyl.testapplication.adapter.LoadingAdapter;
import com.wyl.wyl.testapplication.adapter.PersonAdapter;
import com.wyl.wyl.testapplication.base.BaseActivity;
import com.wyl.wyl.testapplication.bean.PersonMainBean;
import com.wyl.wyl.testapplication.bean.RequestBean;
import com.wyl.wyl.testapplication.utils.CollectionUtils;
import com.wyl.wyl.testapplication.utils.request.RequestCallback;
import com.wyl.wyl.testapplication.utils.request.RequestUtils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import retrofit2.Call;
import retrofit2.Response;

/**
 * 人员页
 *
 * @author 王月玲
 * @time on 2019/4/21 18:42
 */
public class PersonActivity extends BaseActivity {
    public static String voicerLocal = "xiaoyan";
    private TextView store_id;
    private GridView gview;
    private MarqueeView callingTxet;
    private TextView name;
    private TextView position;
    private TextView phoneNumber;
    private ImageView wo1l;
    private LinearLayout personLayout;
    private RelativeLayout callingLayout;
    private List<PersonMainBean.BodyBean.LineingBean> loadingList;
    private List<PersonMainBean.BodyBean.LineingBean> lineingList;
    private List<PersonMainBean.BodyBean.PersonBean> personList;
    private LoadingAdapter loadingAdapter;
    private LineingAdapter lineingAdapter;
    private PersonAdapter personAdapter;
    private ListView listView, listView1;
    private Timer timer;
    private LinearLayout back;
    private Call<PersonMainBean> call;
    // 语音合成对象
    private SpeechSynthesizer mTts;


    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        super.onCreateImpl(savedInstanceState);
        setContentView(R.layout.activity_person);
        mTts = SpeechSynthesizer.createSynthesizer(PersonActivity.this, mTtsInitListener);
        initViews(); // 初始化数据
        initData();
        timer();
    }


    private void initViews() {
        listView1 = (ListView) findViewById(R.id.wait_list_view);
        listView = (ListView) findViewById(R.id.work_list_view);
        wo1l = (ImageView) findViewById(R.id.wo1l);
        store_id = (TextView) findViewById(R.id.store_id);
        callingTxet = (MarqueeView) findViewById(R.id.callingTxet);
        name = (TextView) findViewById(R.id.name);
        phoneNumber = (TextView) findViewById(R.id.phoneNumber);
        position = (TextView) findViewById(R.id.position);
        wo1l = findViewById(R.id.wo1l);
        gview = (GridView) findViewById(R.id.gview);
        personLayout = (LinearLayout) findViewById(R.id.personLayout);
        callingLayout = (RelativeLayout) findViewById(R.id.callingLayout);
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    private void initData() {
        if (mTts == null){
            return;
        }
        mTts.setParameter(SpeechConstant.PARAMS, null);

        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL); //设置云端

        mTts.setParameter(ResourceUtil.TTS_RES_PATH, getResourcePath());
        mTts.setParameter(SpeechConstant.VOICE_NAME, voicerLocal);//设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "45");//设置语速
        //设置合成音调
        mTts.setParameter(SpeechConstant.PITCH, "50");
        mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量，范围0~100
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
    }


    //获取发音人资源路径
    private String getResourcePath() {
        StringBuffer tempBuffer = new StringBuffer();
        //合成通用资源
        tempBuffer.append(ResourceUtil.generateResourcePath(this, RESOURCE_TYPE.assets, "tts/common.jet"));
        tempBuffer.append(";");
        //发音人资源
        tempBuffer.append(ResourceUtil.generateResourcePath(this, RESOURCE_TYPE.assets, "tts/" + PersonActivity.voicerLocal + ".jet"));
        return tempBuffer.toString();
    }


    private void setData(PersonMainBean bean) {
        Log.i("aaa", "更新");
        store_id.setText(bean.getBody().getWh_name());
//        store_time.setText(bean.getBody().getCurrent_date());
        loadingList = bean.getBody().getLoading();
        if (loadingAdapter == null) {
            loadingAdapter = new LoadingAdapter(PersonActivity.this, loadingList);
            listView.setAdapter(loadingAdapter);
        } else {
            loadingAdapter.notifyData(loadingList);
        }
        lineingList = bean.getBody().getLineing();
        for (int i = 0; i < lineingList.size(); i++) {
            Log.i("aaa", "车辆信息 ==== " + lineingList.get(i).getDelivery_vehicle_name());
        }
        if (lineingAdapter == null) {
            lineingAdapter = new LineingAdapter(PersonActivity.this, lineingList);
            listView1.setAdapter(lineingAdapter);
        } else {
            lineingAdapter.notifyData(lineingList);
        }


        if (bean.getBody().getCalling().isEmpty()) {
            personList = bean.getBody().getPerson();
            personLayout.setVisibility(View.VISIBLE);
            callingLayout.setVisibility(View.GONE);
            for (int i = 0; i < personList.size(); i++) {
                PersonMainBean.BodyBean.PersonBean personBean = personList.get(i);
                if (!TextUtils.isEmpty(personBean.getPid()) && personBean.getPid().equals("0")) {
                    Glide.with(PersonActivity.this).load(personBean.getFile_path()).bitmapTransform(new CropCircleTransformation(PersonActivity.this)).into(wo1l);
                    name.setText(personBean.getName());
                    phoneNumber.setText(personBean.getTelephone());
                    position.setText(personBean.getPerson_type());
                    personList.remove(i);
                    break;
                }
            }
            personAdapter = new PersonAdapter(PersonActivity.this, personList);
            gview.setAdapter(personAdapter);
        } else {
            personLayout.setVisibility(View.GONE);
            callingLayout.setVisibility(View.VISIBLE);
            String s = "";
            String speak = "";
            for (int i = 0; i < bean.getBody().getCalling().size(); i++) {
                PersonMainBean.BodyBean.LineingBean bean1 = bean.getBody().getCalling().get(i);
                s += "请" + bean1.getDelivery_vehicle_name() + "到" + bean1.getDoor_code() + "号门装车!" + "\t\t\t\t\t";
                speak += "请，" + bean1.getDelivery_vehicle_name() + "到，" + bean1.getDoor_code() + "号门装车!" + "\t\t\t\t\t";
            }
            read(speak);
            callingTxet.setContent(s);
        }

    }

    private void getData() {
        RequestBean bean = new RequestBean();
        bean.setEquipment_code(CollectionUtils.getDuid(PersonActivity.this));
        RequestUtils.getRetrofit(PersonActivity.this).create(Api.class).getPersonMain(bean)
                .enqueue(new RequestCallback<PersonMainBean>(PersonActivity.this) {
                    @Override
                    public void success(Response<PersonMainBean> response) {
                        Gson gson = new Gson();
                        Log.i("aaa", gson.toJson(response.body(), PersonMainBean.class));
                        setData(response.body());
                    }
                });
    }

    private void timer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                Message message = new Message();
                message.what = 0;
                mHandler.sendMessage(message);
            }
        }, 1000, 30000);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Log.i("aaa", "请求");
                getData();
            }
        }
    };

    /**
     * 开始阅读
     *
     * @param content 内容
     */
    private void read(String content) {
        if (mTts == null){
            return;
        }
        int code = mTts.startSpeaking(content, mTtsListener);
        if (code != ErrorCode.SUCCESS) {
            if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
                //上面的语音配置对象为初始化时：
                Toast.makeText(this, "语音组件未安装", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "语音合成失败,错误码: " + code, Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d("aaa", "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Toast.makeText(PersonActivity.this, "初始化失败,错误码：" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案", Toast.LENGTH_SHORT).show();
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };
    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
//            Toast.makeText(TtsDemo.this, "开始播放", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onSpeakPaused() {
//            Toast.makeText(TtsDemo.this, "暂停播放", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onSpeakResumed() {
//            Toast.makeText(TtsDemo.this, "继续播放", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

        @Override
        public void onCompleted(SpeechError speechError) {
//            Toast.makeText(TtsDemo.this, "完成播放", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
//            Toast.makeText(TtsDemo.this, "播放错误", Toast.LENGTH_SHORT).show();
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}

            //实时音频流输出参考
            /*if (SpeechEvent.EVENT_TTS_BUFFER == eventType) {
                byte[] buf = obj.getByteArray(SpeechEvent.KEY_EVENT_TTS_BUFFER);
				Log.e("MscSpeechLog", "buf is =" + buf);
			}*/
        }
    };

    @Override
    protected void onPauseImpl() {
        super.onPauseImpl();
        timer.cancel();
        call.cancel();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTts == null){
            return;
        }
        mTts.stopSpeaking();
        // 退出时释放连接
        mTts.destroy();
    }
}





